<?php

namespace app\controller;


use app\BaseController;
use app\model\UserRole;
use app\traits\CommonTrait;
use app\validate\UserStore;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\Log;
use think\facade\Request;
use app\model\User;
use think\facade\Session;

class AdminUser extends BaseController
{

    use CommonTrait;

    //创建用户
    public function store()
    {
        $salt = generate_salt();
        $password =  Request::post('password');
        $userData = [
            'name'=>Request::post('name'),
            'phone'=>Request::post('phone'),
            'password'=>$password,
            'company_id'=>Request::post('company_id'),
            'role_id'=>Request::post('role_id'),
            'team_id'=>Request::post('team_id',0),
        ];
        try {
            validate(UserStore::class)->check($userData);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return $this->apiJson(-1, $e->getMessage());
        }
        $userData['head_img'] = 'http://douwuku.qilacps.com/api/images/default_head.png';
        $userData['password'] = password($password,$salt);
        $userData['salt'] = $salt;
        $userData['invite_code'] = $this->generateInviteCode();
        $userData['is_system'] = 1;
        Db::startTrans();
        try {
            $uid = User::create($userData)->getLastInsID();
            UserRole::create(['uid'=>$uid,'rid'=>Request::post('role_id')]);
            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            Log::info('创建用户失败'.$e->getMessage());
            return $this->apiJson(-1,'创建用户失败');
        }
        return $this->apiJson(1,'success');
    }

    //用户信息
    public function getUserInfo()
    {
        $uid = Session::get('uid');
        if(!$uid){
            return $this->apiJson(401,'你未登录');
        }
        $userInfo = User::with(['company'=>function($query){
            $query->field('id,name');
        },'team'=>function($query){
            $query->field('id,name');
        }])->where(['id'=>$uid])
            ->field('id,name,phone,head_img,desc,company_id,team_id,invite_code,status,create_time')
            ->findOrEmpty();
        if($userInfo->isEmpty()){
            return $this->apiJson(-1,'用户不存在');
        }
        if($userInfo['status'] == 2){
            return $this->apiJson(-1,'用户已被禁用');
        }
        $role = UserRole::with(['role'=>function($query){
            $query->field('id,name');
        }])->where(['uid'=>$uid])->whereIn('rid',[1,2,3,4])->find();
        $userInfo['company_id'] = $userInfo['company']?$userInfo['company']['id']:0;
        $userInfo['company_name'] = $userInfo['company']?$userInfo['company']['name']:'';
        $userInfo['role_id'] = isset($role['role']['id'])?$role['role']['id']:0;
        $userInfo['role_name'] = isset($role['role']['name'])?$role['role']['name']:'';
        $userInfo['team_name'] = isset($role['team']['name'])?$role['team']['name']:'';
        unset($userInfo['company']);
        unset($userInfo['team']);
        return $this->apiJson(1,'success',$userInfo);
    }

    //用户列表
    public function userList()
    {
        $currentPage = request()->get('current_page', 1);
        $perPage = $this->getPerPage();
        $companyId = Request::get('company_id',0);
        $teamId = Request::get('team_id','');
        $name = Request::get('name','');
        $startTime = Request::param('start_time') ? strtotime(Request::param('start_time')) : strtotime(date('Y-m-d', time()));
        $endTime = Request::param('end_time') ? strtotime(Request::param('end_time'))+86399 : strtotime(date('Y-m-d', time())) + 86399;
        $where = [];
        if($companyId){
            $where[] = ['company_id','=',$companyId];
        }
        if($teamId){
            $where[] = ['team_id','=',$teamId];
        }
        if($name){
            $where[] = ['name','like','%'.$name.'%'];
        }
        $where[] = ['is_system','=',1];
        if($startTime&&$endTime){
            $where[] = ['create_time','>=',$startTime];
            $where[] = ['create_time','<=',$endTime];
        }
        $user = User::with(['invite'=>function($query){
            $query->field('id,name');
        },'company'=>function($query){
            $query->field('id,name');
        },'team'=>function($query){
            $query->field('id,name');
        }])->where($where)->field('id,head_img,name,phone,company_id,team_id,invite_uid,status,create_time')
            ->paginate(['page'=>$currentPage,'list_rows'=>$perPage]);

        foreach ($user as &$v){
            $v['company_name'] = $v['company']['name'];
            if(is_null($v['team'])){
                $v['team_name'] = '';
            }else{
                $v['team_name'] = $v['team']['name'];
            }
            if(is_null($v['invite'])){
                $v['invite_name'] = '';
            }else{
                $v['invite_name'] = $v['invite']['name'];
            }
            unset($v['company']);
            unset($v['team']);
            unset($v['invite']);
        }
        return $this->apiJson(1,'success',$user);
    }

    public function statusOperation()
    {
        $uid = Request::post('uid');
        if(!$uid){
            return $this->apiJson(-1,'缺少uid参数');
        }
        $userExist = User::where(['id'=>$uid,'is_system'=>1])->field('id,status')
            ->findOrEmpty();
        if($userExist->isEmpty()){
            return $this->apiJson(-1,'用户不存在');
        }
        if($userExist['status'] == 1){
            $userExist->status = 2;
            $userExist->save();
        }else{
            $userExist->status = 1;
            $userExist->save();
        }
       return $this->apiJson(1,'success');
    }

    public function edit()
    {

    }

}